package org.mspring.mlog.action.admin;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.mspring.mlog.QiniuService;
import org.mspring.nbee.common.utils.CollectionUtils;
import org.mspring.nbee.common.utils.HttpUtils;
import org.mspring.nbee.common.utils.RequestUtils;
import org.mspring.nbee.web.Action;
import org.mspring.nbee.web.support.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Gao Youbo
 * @since 2015-02-28 17:56
 */
@Action
@RequestMapping("/admin/common")
public class CommonAction {
    private static final Logger LOG = LoggerFactory.getLogger(CommonAction.class);

    private QiniuService qiniuService;

    /**
     * 上传图片
     *
     * @param file
     * @param context
     * @param model
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping("/image/upload")
    public void imageUpload(@RequestParam MultipartFile file, WebContext context, Model model) throws IOException, ServletException {
        QiniuService.UploadResult result = qiniuService.upload(file.getBytes());
        context.renderJsonResult(result);
    }

    /**
     * 获取html片段中的远程图片，并将其上传到自己的服务器
     *
     * @param context
     * @param model
     */
    @RequestMapping("/image/remote")
    public void imageRemote(WebContext context, Model model) {
        String html = RequestUtils.getParam(context.getRequest(), "html");
        if (StringUtils.isBlank(html)) {
            context.renderJsonResult(false);
        }
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img");
        if (CollectionUtils.isEmpty(imgs)) {
            context.renderJsonResult(false);
        }
        List<QiniuService.UploadResult> results = new ArrayList<>();
        for (Element img : imgs) {
            String original = img.absUrl("src"); //原始的图片URL
            if (StringUtils.contains(original, "file.mspring.org")) { //如果本身就是自己的图片，那么跳过
                continue;
            }
            try {
                QiniuService.UploadResult result = HttpUtils.httpGet(original, null, new HttpUtils.ResponseHandler<QiniuService.UploadResult>() {
                    @Override
                    public QiniuService.UploadResult handle(HttpResponse response) {
                        try {
                            byte[] data = IOUtils.toByteArray(response.getEntity().getContent());
                            return qiniuService.upload(data);
                        } catch (Exception e) {
                            LOG.error(null, e);
                        }
                        return null;
                    }
                });
                results.add(result);
                Attributes attributes = new Attributes();
                attributes.put("src", result.getUrl() + "!detail");
                attributes.put("class", "article-content-image");
                Node newImage = new Element(Tag.valueOf("img"), "", attributes);
                img.replaceWith(newImage);

                LOG.info("成功下载远程图片：{}， 新地址：{}", original, result.getUrl());
            } catch (Exception e) {
                LOG.error(null, e);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("html", doc.html());
        map.put("imageList", results);
        context.renderJsonResult(map);
    }


    @Autowired
    public void setQiniuService(QiniuService qiniuService) {
        this.qiniuService = qiniuService;
    }
}
